import asyncio
from communication.webrtc_handler import WebRTCHandler
from communication.video_stream import VideoStreamer
from vehicle.vehicle_controller import VehicleController

class Scheduler:
    def __init__(self, args):
        self.vehicle_controller = VehicleController(args.controller_type)
        self.video_streamer = VideoStreamer()
        self.webrtc_handler = WebRTCHandler(
            on_datachannel=self.on_datachannel,
            on_video_request=self.on_video_request
        )
    
    async def start(self):
        """启动调度器"""
        await self.webrtc_handler.start_signaling()
    
    def on_datachannel(self, channel):
        """处理WebRTC数据通道"""
        @channel.on("message")
        def on_message(message):
            try:
                cmd = json.loads(message)
                self.vehicle_controller.send_command(cmd)
            except Exception as e:
                print(f"Command error: {e}")
        
        # 定期发送传感器数据
        async def send_sensor_data():
            while channel.readyState == "open":
                channel.send(json.dumps({
                    "type": "sensors",
                    "data": self.vehicle_controller.get_sensor_data()
                }))
                await asyncio.sleep(0.2)  # 5Hz
        
        asyncio.create_task(send_sensor_data())
    
    def on_video_request(self):
        """处理视频请求"""
        self.video_streamer.start_streaming(self.webrtc_handler)